<script lang="js" setup>
import {onMounted, reactive, ref} from 'vue';
import {SearchOutlined, MessageOutlined} from '@ant-design/icons-vue'; //组件库
import {useRouter} from 'vue-router'  //前端路由
import axios from "axios";
import {message} from "ant-design-vue";
import ChatPopup from "../chat/chatOne.vue"    //前后端连接
const chatButton = ref(false)
const categories = ref([
  {
    name: '精装公寓',
    desc: '品质装修 拎包入住',
    imageUrl: 'http://192.168.137.100:9000/other/1.jpg',
    value:0
  },
  {
    name: '地铁房源',
    desc: '交通便利 通勤无忧',
    imageUrl: 'http://192.168.137.100:9000/other/2.jpg',
    value: 1
  },
  {
    name: '品质豪宅',
    desc: '尊贵享受 品质生活',
    imageUrl: 'http://192.168.137.100:9000/other/3.jpg',
    value: 2
  },
  {
    name: '优质合租',
    desc: '温馨共享 交友社交',
    imageUrl: 'http://192.168.137.100:9000/other/4.jpg',
    value: 3
  },
  {
    name: '商铺办公',
    desc: '繁华地段 商机无限',
    imageUrl: 'http://192.168.137.100:9000/other/5.jpg',
    value: 4
  }
]);

const logoUrl = 'http://192.168.137.100:9000/other/logo.png';
const minPrice = ref();
const maxPrice = ref();
const priceDown = ref(false);
const selectedArea = ref('不限'); //地区选择
const selectedPrice = ref('不限');  //价钱选择
const selectedRoom = ref(0); //户型选择
const number = ref();
const num = ref(0);
const data1 = reactive({
  provinceId: null,  //省
  cityId: 1501,       //城市
  districtId: null,   //区域
  minRent: null,       //最少租金
  maxRent: null,       //最大租金
  type: null,          //房子样式
  orderType: "asc",     //升序排列
});
const areas = ref([]);  //区
const prices = ['不限', '1000元以下', '1000-2000元', '2000-3000元', '3000-4500元', '4500-6000元', '6000元以上'];
const rooms = ['不限', '一室一厅', '两室一厅', '两室两厅', '三室一厅', '三室两厅', '四室一厅', '四室两厅', '五室两厅', '复式', '别墅', '单间', '开间'];
//房子信息
const recommendHouses = ref([]);
const router = useRouter();
const getNum = async () => {
  try {
    num.value = 0;
    if(sessionStorage.getItem("cityId")){
      data1.cityId = sessionStorage.getItem("cityId");
    }
    const json = JSON.stringify(data1);
    console.log("限制：" + json)
    const response = await axios.post(`${window.link}/house/pageItem?current=${num.value}&size=12`, json, {
      headers: {
        "Content-Type": "application/json", // 明确设置为 JSON 类型
      },
    });
    console.log("总量")
    console.log(response);
    const {total} = response.data.data;
    number.value = total;
    renderPagination();
  } catch (error) {
    console.error("Failed to fetch association data:", error);
  }
};

const getHouse = async () => {
  try {
    const json = JSON.stringify(data1)
    const response = await axios.post(
        `${window.link}/house/pageItem?current=${num.value}&size=12`, json, {
          headers: {
            "Content-Type": "application/json", // 明确设置为 JSON 类型
          },
        }
    );
    console.log(response)
    const {message, code} = response.data;
    if (code === 200) {
      // 成功处理逻辑
      recommendHouses.value = response.data.data.records;
    } else {
      // 错误处理逻辑
      alert(message);
    }
  } catch (error) {
    // 异常处理逻辑
    console.error("获取房子信息", error);
  }
};
const renderPagination = () => {
  layui.use(function () {
    var laypage = layui.laypage;
    // 自定义主题
    laypage.render({
      elem: 'demo-laypage-theme-1',
      count: number.value,
      limit: 12,
      theme: '#f97316',
      jump: function (obj) {
        num.value = obj.curr;
        getHouse();
      }
    });
  });
}
const setArea = async () => {
  let id = 1501;
  if (sessionStorage.getItem("cityId")) {
    id = sessionStorage.getItem("cityId")
  }
  try {
    const response = await axios.get(`${window.link}/location/district/${id}`);
    console.log(response)
    if (response.data.code === 200) {
      areas.value = response.data.data
      console.log(areas.value)
    } else {
      message.error(response.data.message);
    }
  } catch (error) {
    console.error("获取区域失败", error)
  }
}

const containerArea = (area) => {
  if (area === '不限') {
    selectedArea.value = area
    data1.districtId = null;
    return
  }
  selectedArea.value = area
  data1.districtId = selectedArea.value
  getNum();
}
const containerPrice = (price) => {
  selectedPrice.value = price
  // 不限', '1000元以下', '1000-2000元', '2000-3000元', '3000-4500元', '4500-6000元', '6000元以上
  console.log(price)
  if (price === '1000元以下') {
    minPrice.value = 0
    maxPrice.value = 1000
  } else if (price === '1000-2000元') {
    minPrice.value = 1000;
    maxPrice.value = 2000;
  } else if (price === '2000-3000元') {
    minPrice.value = 2000;
    maxPrice.value = 3000;
  } else if (price === '3000-4500元') {
    minPrice.value = 3000;
    maxPrice.value = 4500;
  } else if (price === '4500-6000元') {
    minPrice.value = 4500;
    maxPrice.value = 6000;
  } else if (price === '6000元以上') {
    minPrice.value = 6000;
    maxPrice.value = null;
  } else {
    maxPrice.value = null;
    minPrice.value = null;
  }
  data1.minRent = minPrice.value;
  data1.maxRent = maxPrice.value
  getNum();
}

const containerType = (type) => {
  selectedRoom.value = type
  if (type === 0) {
    type = null;
  } else {
    type = type + 1;
  }
  data1.type = type
  getNum();
}

const containerSearch = () => {
  getNum();
}
const containerPriceDown = () => {
  if (priceDown.value) {
    data1.orderType = 'desc'
  } else {
    data1.orderType = 'asc'
  }
  getNum();
}

const description = (id) => {
  sessionStorage.setItem("houseId", id)
  router.push("/house")
}

const goLandlord = () => {
  router.push("/landlord")
}

const showChat = ref(false)
const openChat = () => {
  showChat.value = true;
};
const chatButton1 = ()=>{
  if (localStorage.getItem("access-token")) {
    chatButton.value = true;
  }
}
const containerQuickSelect = (value,name) => {
  sessionStorage.setItem("typeValue", value);
  sessionStorage.setItem("typeName",name)
  router.push(`/home/quickSelect?type=${name}`);
}
const houseStatus = async ()=>{
  try{
    const response = await axios.get(`${window.link}/user/contract/prompt`,{
      headers:{
        "access-token":localStorage.getItem("access-token")
      }
    })
    console.log("houseStatus");
    console.log(response)
    const items =  response.data.data;
    let number = 0;
    for(let item in items){
      if(items[item].isPrompt){
        number++;
      }
    }
    if(number !== 0){
      alert(`您有${number}个房子即将到期，请在前往个人中心->订单信息页面续费或退租`)
    }
  }catch (error){
    console.log("请求租房到期状态错误",error)
  }
}

const videoExtensions = ['mp4', 'webm', 'ogg']
const isVideo = (url) => {
  const extension = url.split('.').pop().toLowerCase()
  return videoExtensions.includes(extension)
}

houseStatus();
getNum();
chatButton1();
setArea();
</script>

<template>
  <!-- Logo和搜索区 -->
  <div class="bg-white border-b">
    <div class="container mx-auto px-8 py-6">
      <div class="flex items-center justify-between">
        <!-- Logo -->
        <div class="flex-shrink-0">
          <img :src="logoUrl" alt="Logo" class="h-12">
        </div>

        <!-- 搜索框 -->
        <div class="flex-1 max-w-3xl ml-4">
          <div class="relative flex justify-center items-center" :style="{padding: '20px'}">
            <a-input-search
                v-model:value="data1.search"
                placeholder="请输入房屋名称，或描述"
                size="large"
                :style="{ width: '100%'}"
            >
              <template #enterButton>
                <a-button type="primary"
                          class="bg-orange-500 hover:bg-orange-600"
                          :style="{ maxHeight: '39px', border: 'none', boxShadow: 'none' }"
                          @click="containerSearch"
                >
                  <template #icon>
                    <search-outlined/>
                  </template>
                  搜索房源
                </a-button>
              </template>
            </a-input-search>
          </div>
        </div>

      </div>
    </div>
  </div>
  <!-- 分类快速入口 -->
  <div class="bg-white py-12">
    <div class="container mx-auto px-8">
      <div class="grid grid-cols-5 gap-8">
        <div v-for="(category, index) in categories" :key="index" @click="containerQuickSelect(category.value,category.name)"
             class="group cursor-pointer transform transition-transform duration-200 hover:-translate-y-1">
          <div class="relative h-48 rounded-lg overflow-hidden shadow-lg">
            <img :src="category.imageUrl" :alt="category.name"
                 class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110">
            <div class="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent"></div>
            <div class="absolute bottom-0 left-0 p-4 text-white">
              <h3 class="text-lg font-medium mb-1">{{ category.name }}</h3>
              <p class="text-sm opacity-90">{{ category.desc }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- 筛选区域 -->
  <div class="container mx-auto mt-8 mb-6">
    <div class="bg-white rounded-lg shadow-md p-6">
      <div class="space-y-6">
        <div class="flex items-start">
          <span class="w-20 flex-shrink-0 text-gray-600 font-medium pt-2">区域</span>
          <div class="flex-1">
            <div class="flex flex-wrap gap-x-8 gap-y-4">
                <span v-for="area in areas" :key="area" @click="containerArea(area.id)"
                      class="text-gray-600 hover:text-orange-500 cursor-pointer"
                      :class="{'text-orange-500 font-medium': area.id === selectedArea}">
                  {{ area.name }}
                </span>
            </div>
          </div>
        </div>
        <div class="flex items-start">
          <span class="w-20 flex-shrink-0 text-gray-600 font-medium pt-2">租金</span>
          <div class="flex-1">
            <div class="flex flex-wrap items-center gap-8">
                <span v-for="price in prices" :key="price" @click="containerPrice(price)"
                      class="text-gray-600 hover:text-orange-500 cursor-pointer"
                      :class="{'text-orange-500 font-medium': price === selectedPrice}">
                  {{ price }}
                </span>
              <div class="flex items-center space-x-3">
                <a-input-number v-model:value="data1.minRent" :min="0" class="!w-28" placeholder="最低价"
                                @blur="getNum"/>
                <span class="text-gray-400">-</span>
                <a-input-number v-model:value="data1.maxRent" :min="0" class="!w-28" placeholder="最高价"
                                @blur="getNum"/>
                <span class="text-gray-600 ml-2">元/月</span>
              </div>
            </div>
          </div>
        </div>
        <div class="flex items-start">
          <span class="w-20 flex-shrink-0 text-gray-600 font-medium pt-2">户型</span>
          <div class="flex-1">
            <div class="flex flex-wrap gap-x-8 gap-y-4">
                <span v-for="(room,index) in rooms" :key="room" @click="containerType(index)"
                      class="text-gray-600 hover:text-orange-500 cursor-pointer"
                      :class="{'text-orange-500 font-medium': index === selectedRoom}">
                  {{ room }}
                </span>
            </div>
          </div>
        </div>
        <div class="flex items-start">
          <span class="w-20 flex-shrink-0 text-gray-600 font-medium pt-2">筛选</span>
          <div class="flex-1">
            <div class="flex items-center flex-wrap gap-6">
              <a-checkbox v-model:checked="priceDown" @update:checked="containerPriceDown">按价钱降序排列</a-checkbox>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- 内容区域 -->
  <div class="container mx-auto mb-12">
    <a-tabs class="bg-white rounded-lg shadow-md">
      <a-tab-pane key="1" tab="推荐房源">
        <div class="min-h-[600px] p-6">
          <div class="grid grid-cols-2 gap-6">
            <div v-for="house in recommendHouses" :key="house.id"
                 class="flex bg-white rounded-lg overflow-hidden hover:shadow-lg transition-shadow duration-300"
            >
              <div class="w-64 h-48 flex-shrink-0">
                <img v-if="!isVideo(house.graphUrl)" :src="house.graphUrl" :alt="house.title"
                     class="w-full h-full object-cover">
                <video v-else :src="house.graphUrl" controls
                       class="w-full h-full object-cover"></video>
              </div>
              <div class="flex-1 p-4">
                <h3 class="text-lg font-medium mb-2 line-clamp-1">{{ house.title }}</h3>
                <div class="flex items-center text-sm text-gray-500 mb-2">
                  <span>{{ house.district }}</span>
                  <span class="mx-2">|</span>
                  <span>{{ house.layout }}</span>
                  <span class="mx-2">|</span>
                  <span>{{ house.area }}</span>
                </div>
                <div class="flex items-center justify-between mt-auto">
                  <div class="flex items-baseline">
                    <span class="text-2xl font-medium text-orange-500">{{ house.rent }}</span>
                    <span class="text-gray-500 text-sm ml-1">元/月</span>
                  </div>
                  <a-button type="primary" class="!rounded-button whitespace-nowrap cursor-pointer"
                            @click="description(house.id)">
                    查看详细
                  </a-button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div id="demo-laypage-theme-1" style=" bottom: 0; width: 100%;  text-align: center; padding: 10px;"></div>
      </a-tab-pane>
    </a-tabs>
  </div>
  <!-- 添加悬浮聊天气泡 -->
  <div class="fixed right-8 bottom-8 z-50">
    <a-button
        v-if="chatButton"
        type="primary"
        shape="circle"
        size="large"
        class="w-14 h-14 flex items-center justify-center bg-orange-500 hover:bg-orange-600 border-none shadow-lg"
        @click="openChat"
    >
      <message-outlined class="text-xl"/>
    </a-button>
  </div>

  <ChatPopup
      v-if="showChat"
  />
<!--  v-model:visible="showChat"-->

</template>


<style scoped>
</style>
